package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.LogItem;
import cc.eddic.practice.concurrency.LogParser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;


public class LogParserWithLoopScwImpl implements LogParser {
    @Override
    public Map<String, List<LogItem>> parse(String folderName) {
        Map<String, List<LogItem>> resultMap = new HashMap<>();
        File fileFolder = new File(folderName);
        traverseFolder(fileFolder, resultMap);
        return resultMap;
    }

    private List<LogItem> parseLogFile(String path) throws IOException {
        List<LogItem> logItems = new ArrayList<>();
        LogItemParserScwImpl logItemParser = new LogItemParserScwImpl();
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line;
            while ((line = reader.readLine()) != null) {
                Optional<LogItem> parsedLogItem = logItemParser.parse(line);
                parsedLogItem.ifPresent(logItems::add);
            }
        }
        return logItems;
    }

    private void traverseFolder(File fileFolder, Map<String, List<LogItem>> resultMap) {
        File[] files = fileFolder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    traverseFolder(file, resultMap);
                } else if (file.getName().endsWith(".log")) {
                    try {
                        List<LogItem> logItems = parseLogFile(file.getAbsolutePath());
                        resultMap.put(file.getAbsolutePath(), logItems);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}


